package com.wkhyapp.lm.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.wkhyapp.lm.R;
import com.wkhyapp.lm.adapter.HostAdapter;
import com.wkhyapp.lm.base.SuperActivity;
import com.wkhyapp.lm.constant.Constant;
import com.wkhyapp.lm.contract.SearchPresenter;
import com.wkhyapp.lm.contract.SearchView;
import com.wkhyapp.lm.http.vo.Member;
import com.wkhyapp.lm.utils.IdUtils;
import com.wkhyapp.lm.utils.MemberUtils;
import com.wkhyapp.lm.utils.PreferenceUtils;
import com.wkhyapp.lm.utils.StatusBarFontUtil;
import com.wkhyapp.lm.weigit.EditTextWithDel;
import com.wkhyapp.lm.weigit.FlowLayout;
import com.wkhyapp.lm.weigit.flowlayout.TagAdapter;
import com.wkhyapp.lm.weigit.flowlayout.TagFlowLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2021-10-3.
 */

public class SearchActivity  extends SuperActivity<SearchPresenter> implements SearchView{

    private static final int REQUEST_CAMERA_CODE = 10;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private ArrayList<String> imgList = new ArrayList<>();
    @BindView(R.id.del_iv)
    ImageView del_iv;
    @BindView(R.id.gridView_iv)
    GridView gridView_iv ;
    private HostAdapter hosatAdapter;
    private List<Member> members;
    @BindView(R.id.xcss_iv)
    ImageView xcss_iv;
    @BindView(R.id.back_iv)
    ImageView back;
    String url;
    @BindView(R.id.search_et)
    EditText editTextWithDel;
    private String key;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout mFlowLayout;
    private LayoutInflater mInflater;
    private TextView tv;
    List<String> searchKeys = new ArrayList<>();
    @Override
    public void initUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            translucentStatusBar();
        }
        StatusBarFontUtil.setLightStatusBarColor(this);
        mInflater = LayoutInflater.from(this);
        members = new ArrayList<>();
        hosatAdapter  = new HostAdapter(mContext,members,R.layout.item_host_member);
        gridView_iv.setAdapter(hosatAdapter);
        mPresenter.getData();

        initKey();
        editTextWithDel.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keyword = v.getText().toString().trim();
                     goTo(SearchResultActivity.class,keyword);
                    return true;
                }
                return false;
            }
        });
    }



    public  void initKey(){
        List<String> list= gson.fromJson(PreferenceUtils.getInstance().getPrefString("keys",""), new TypeToken<List<String>>() {}.getType());
        if(list!=null){
            mFlowLayout.setVisibility(View.VISIBLE);
            searchKeys.addAll(list);
            mFlowLayout.setAdapter(new TagAdapter(searchKeys) {
                @Override
                public View getView(com.wkhyapp.lm.weigit.flowlayout.FlowLayout parent, int position, Object o) {
                    tv = (TextView) mInflater.inflate(R.layout.tv, mFlowLayout, false);
                    tv.setText(o.toString());
                    return tv;
                }
            });
            Log.e("searchKeys",searchKeys.size()+"");
            if(searchKeys.size()>0){
                del_iv.setVisibility(View.VISIBLE);
            }else{
                del_iv.setVisibility(View.GONE);
            }
        }else{
            mFlowLayout.setVisibility(View.GONE);
            del_iv.setVisibility(View.GONE);
        }
    }

    @Override
    protected void afterCreate() {


    }

    @Override
    protected void initListener() {
        del_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PreferenceUtils.getInstance().setPrefString("keys",null);
                 initKey();

            }
        });
        gridView_iv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              goTo(ShopActivity.class,members.get(position).getId());
            }
        });



        xcss_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }else{
                    PhotoPickerIntent intent = new PhotoPickerIntent(SearchActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(false); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                }

            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        //流式布局tag的点击方法
        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, com.wkhyapp.lm.weigit.flowlayout.FlowLayout parent) {
                goTo(SearchResultActivity.class,searchKeys.get(position));
                return true;
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }
    @Override
    protected SearchPresenter createPresenter() {
        return mPresenter = new SearchPresenter(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    Log.d(TAG, "数量：" + list.size());
                    imgList.addAll(list);
                    if(list.size()>0){
                        mPresenter.getToken();
                    }
                    break;
            }
        }
    }


    @Override
    public void setHostMember(List<Member> list) {
        members.addAll(list);
        hosatAdapter.notifyDataSetChanged();
    }

    Configuration config = new Configuration.Builder().build();
    UploadManager uploadManager = new UploadManager(config);
    @Override
    public void setToken(String token) {
        String key = "sousuo_"+MemberUtils.getMember()+"_"+System.currentTimeMillis()+"_"+ IdUtils.getShartUUID();
        uploadManager.put(imgList.get(0), key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if(info.isOK()) {
                            goTo(SearchResultActivity.class, Constant.qiniuUrl+key);
                        } else {
                        }
                    }
                }, null);
         }


    @Override
    public void onResume() {
       super.onResume();
        initKey();
    }
}
